package com.qq.BFMRSE.BF_MRSEController;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.qq.BFMRSE.Hdfs.hdfsOper;
import com.qq.BFMRSE.Module.upLoadTool;
import com.qq.BFMRSE.util.BFConstants;

@Controller
public class handlerNewEncryFile {
	@RequestMapping(value= "/newEncryFile",method=RequestMethod.POST)
	public void handler(HttpServletRequest request,HttpServletResponse response){
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		Logger log=Logger.getLogger(handlerNewEncryFile.class);
		FileItemFactory factory=new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory); 
		File directory=null;
		String filePath="";
		String userName="";
		List<FileItem> items=new ArrayList<FileItem>();
		try {
			items=upload.parseRequest(request);
			if(items.size()!=0){
				FileItem tempItem=items.get(0);
				if(tempItem.isFormField()){
					userName=tempItem.getString("utf-8");
					filePath=userName+File.separator+BFConstants.ENCRYDIRNAME;
					if(!hdfsOper.isFileExist(filePath)||!hdfsOper.isDirectory(filePath)){
						if(hdfsOper.mkdir(filePath)){
							log.info("User:"+userName+"create directory in hdfs");
						}
					}
				}
				upLoadTool ut=new upLoadTool(userName, BFConstants.UPENCRYPTFILE, null);
				ut.upLoadToHdfs(items);
				log.info("User:"+userName+" upload files to hdfs.");
			}	
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			log.error("read filesLoad http request error!");
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		PrintWriter out=null;
		 try {  
		        out = response.getWriter();
		        out.println("success");
		    } catch (IOException e) {  
		        e.printStackTrace();  
		    } finally {  
		        if (out != null) {  
		        	out.flush();
		            out.close();  
		        }  
		    }  
	}

}
